package com.java.simple.smallspring.bean;

import com.java.simple.smallspring.beans.factory.FactoryBean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhoujunlin
 * @date 2022年08月29日 13:22
 * @desc
 */
public class ProxyBeanFactory implements FactoryBean<IUserDao> {

    @Override
    public IUserDao getObject() throws Exception {
        InvocationHandler handler = (proxy, method, args) -> {
            // 添加排除方法
            if ("toString".equals(method.getName())) {
                return this.toString();
            }
            if ("hashCode".equals(method.getName())) {
                return this.hashCode();
            }
            Map<String, String> userMap = new HashMap<>();
            userMap.put("10001", "张三");
            userMap.put("10002", "里斯");
            userMap.put("10003", "王五");
            return "你被代理了 " + method.getName() + " : " + userMap.get(args[0].toString());
        };
        return (IUserDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{IUserDao.class}, handler);
    }

    @Override
    public Class<?> getObjectType() {
        return IUserDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
